package com.antrain.core;

import java.lang.reflect.Field;
import java.util.*;

import com.antrain.utils.JDBCUtil;

@SuppressWarnings("rawtypes")
public class ORMSession {

    /**
     * ORMConfig 获取实体表的映射信息
     * 
     * @param clz
     * @return
     */
    private Mapper getTableMapper(Class clz) {
        Mapper mapper = null;
        List<Mapper> mappers = ORMConfig.geMapperList();
        // 遍历集合，找到和entity类对应的mapper对象
        for (Mapper mapper2 : mappers) {
            if (mapper2.getClassName().equals(clz.getName())) {
                mapper = mapper2;
                break;
            }
        }
        if (mapper == null) {
            throw new RuntimeException("该实体类未配置");
        }
        return mapper;
    }

    private String getValue(Field field, Object entity) {
        try {
            // 设置可以访问私有属性
            field.setAccessible(true);
            // 根据属性得到它的值
            return field.get(entity).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 往实体类表中插入一条数据
     * 
     * @param entity 实体类
     * @return
     */
    public int insert(Object entity) {
        String sql = null;
        Mapper mapper = getTableMapper(entity.getClass());
        String tableName = mapper.getTableName();
        StringBuilder insertSql1 = new StringBuilder("insert into `" + tableName + "` (");
        StringBuilder insertSql2 = new StringBuilder(" ) values ( ");
        // 得到当前对象所属类中的所有属性
        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 根据属性得到字段名
            insertSql1.append(mapper.getPropMapper().get(field.getName()) + ",");
            insertSql2.append("'" + getValue(field, entity) + "',");
        }
        // 6 拼接字符串
        insertSql1.deleteCharAt(insertSql1.length() - 1);
        insertSql2.deleteCharAt(insertSql2.length() - 1).append(");");
        sql = insertSql1.toString() + insertSql2.toString();
        System.out.println("insert sql ---" + sql);
        // 7 通过JDBCUtil发送并执行sql
        return JDBCUtil.executeUpdate(sql);
    }

    public int update(Object entity) {
        return 0;
    }

    /**
     * 根据主键从实体类表删除一条记录
     * 
     * @param entity 实体类
     * @return
     */
    public int delete(Object entity) {
        Mapper mapper = getTableMapper(entity.getClass());
        StringBuilder sql = new StringBuilder("delete from `");
        sql.append(mapper.getTableName() + "` where ");
        // 4 得到主键的字段名和属性名
        Object[] idProp = mapper.getIdMapper().keySet().toArray();
        Object[] idCol = mapper.getIdMapper().values().toArray();
        try {
            // 5 根据主键得到它的值
            Field field = entity.getClass().getDeclaredField(idProp[0].toString());
            // 6 拼接字符串
            sql.append(idCol[0].toString() + " = " + getValue(field, entity) + ";");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("delete sql ---" + sql);
        // 7 通过JDBCUtil发送并执行sql
        return JDBCUtil.executeUpdate(sql.toString());
    }

    /**
     * 根据主键从实体表获取一条数据
     * @param clz
     * @param id
     * @return
     */
    public Object queryOne(Class clz, Object id) {
        Mapper mapper = getTableMapper(clz);
        StringBuilder sql = new StringBuilder("select * from `");
        sql.append(mapper.getTableName() + "` where ");
        //  得到主键的字段名和属性名
        Object[] idCol = mapper.getIdMapper().values().toArray();
        sql.append(idCol[0].toString() + " = " + id + ";");
        System.out.println("queryOne sql ---" + sql);
        // 7 通过JDBCUtil发送并执行sql
        return JDBCUtil.excuteQuery(sql.toString(), clz, mapper);
    }
}